<?php

namespace app\yunda\validate;
use think\Validate;
use app\yunda\model\User as UserModel;
/**
 * 用户数据验证
 * @package app\yunda\validate
 */
class User extends Validate
{
    //定义验证规则
    protected $rule = [
        'openid|微信id'  => 'require',
        'phone|手机号' => 'require|unique:yd_user|regex:^1[3,5,6,7,8]{1}\d{9}$',
        'code|验证码'  => 'require',
        'password|密码'  => 'require|length:6,20',
        'repassword|确认密码'  => 'require|confirm:password|length:6,20',
        'name|用户名'  => 'require',
    ];

    //定义验证提示
    protected $message = [
        'phone.regex' => '手机号码不正确',
        'password.length' => '密码长度为6-20位',
        'repassword.length' => '确认密码长度为6-20位',
        'repassword.confirm' => '确认密码不正确',
    ];

    //定义验证场景
    protected $scene = [
        'login'=>['openid','phone'=>'require|checkPhone','password'=>'require|checkPwd'],
        'register'=>['openid'=>'checkOpenid','phone'=>'checkPhone1','code'=>'checkCode','password','repassword'],
        'person'=>['name'],
    ];


    protected function checkPhone($value,$rule)
    {
        $row=UserModel::get(['phone'=>$value]);
        return $rule= empty($row) ? '用户不存在':true;
    }

    protected function checkPwd($value,$rule,$data)
    {
        $value=md5($value);
        $row=UserModel::get(['password'=>$value,'phone'=>$data['phone']]);
        return $rule= empty($row) ? '密码错误':true;
    }

    protected function checkPhone1($value,$rule)
    {
        $row=UserModel::get(['phone'=>$value]);
        return $rule= empty($row) ? true:'账号已存在';
    }

    protected function checkCode($value,$rule,$data)
    {
        $row=UserModel::get(['code'=>$value,'openid'=>$data['openid']]);
        if($row['yzm_time']+600>time()) return $rule='验证码超时';
        return $rule= empty($row) ? '验证码错误':true;
    }

    protected function checkOpenid($value,$rule)
    {
        $row=UserModel::get(['openid'=>$value]);
        return $rule= empty($row) ? '用户未授权登录':true;
    }


}
